#include "EventEngine.h"
#include "PluginManager.h"

EventEngine EventEngine::sInst;

class EventEnginePrivate{
public:
    using PluginMap = QHash<QString,BasePlugin*>;
    QHash<Event, PluginMap> mEventMap;
    friend class EventEngine;
};

void EventEngine::DipatchEvent(Event event, void *pData, BasePlugin *pSender)
{
    if(_p->mEventMap.contains(event)){
        //待通知的插件
        auto pluginMap = _p->mEventMap[event];
        //遍历并回调
        for(auto plugin : pluginMap){
            plugin->HandleEvent(event,pData,pSender);
        }
    }
}

void EventEngine::RegisterEvent(Event event, BasePlugin *pSender)
{
    if(_p->mEventMap.contains(event)){
        auto pluginMap = _p->mEventMap[event];
        pluginMap.insert(pSender->GetName(), pSender);
    }else{
        PluginMap pluginMap;
        pluginMap.insert(pSender->GetName(), pSender);
        _p->mEventMap.insert(event,pluginMap);
    }
}

void EventEngine::UnregisterEvent(Event event, BasePlugin *pSender)
{
    if(_p->mEventMap.contains(event)){
        auto pluginMap = _p->mEventMap[event];
        if(pluginMap.contains(pSender->GetName())){
            pluginMap.remove(pSender->GetName());
        }
    }
}

EventEngine::EventEngine():QObject(),_p(new EventEnginePrivate)
{

}

EventEngine::~EventEngine()
{
    if(_p){
        delete _p;
        _p = nullptr;
    }
}
